package com.heima.common.exception;

import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobleExceptionHandler {


    @ExceptionHandler(RuntimeException.class)
    public ResponseResult RuntimeException(Exception e){
        return ResponseResult.error(AppHttpCodeEnum.SERVER_ERROR);

    }

    @ExceptionHandler(LeadException.class)
    public ResponseResult leadException(LeadException le){

        return ResponseResult.error(le.getStatus(),le.getMessage());

    }

    /**
     * 未定义的异常
     * @param throwable
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public ResponseResult throwableHandler(Throwable throwable){

        return ResponseResult.error(AppHttpCodeEnum.SERVER_ERROR);

    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult methodArgumentNotValidException(MethodArgumentNotValidException m){
        log.error(m.getMessage());
        BindingResult bindingResult = m.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        String msg = allErrors.stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.joining(";"));
        return new ResponseResult(400,msg);

    }

}
